
import router from './routers'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/sso', '/change-password','/success-password']

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  if (to.path == '/browser' || to.path == '/login') {
    next()
  } else {
    if (getToken()) {
      to.meta.title && store.dispatch('settings/setTitle', to.meta.title) //tag的title
      // 路由
      /* has token*/
      if (to.path == '/login' ) {
        next()
      }else{
        console.log(store.getters['permission_routes'],'store.getters');
        if (!store.getters['permission_routes'].length > 0) { // 判断是否已经生成过路由
            try {
                let accessRoutes = await store.dispatch('GenerateRoutes') // 在此处调用 generateRoutes 方法
                router.addRoutes(accessRoutes)
                next({ ...to, replace: true })
            } catch (error) {
                console.error(error)
            }
        } else {
            console.log('3------------');
            next()
        }
      } 
    } else {
        // 没有token
        if (whiteList.indexOf(to.path) !== -1) {
          // 在免登录白名单，直接进入
          next()
        } else {
          next(`/login`) // 否则全部重定向到登录页
        }
    }
  }
  NProgress.done()
})
router.afterEach(() => {
  NProgress.done()
})
